package elitequant.gui;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import elitequant.data.TickEvent;
import elitequant.event.Event;
import elitequant.event.EventHandler;
import elitequant.event.EventType;
import elitequant.event.LiveEventEngine;
import elitequant.util.UtilFunc;

public class MarketWindow extends JPanel implements EventHandler {

    private static final long serialVersionUID = -4877217174711742589L;

    private LiveEventEngine eventsEngine;

    private JTable jTable;
    
    private DefaultTableModel tableModel;
    
    private String[] symbols;

    private String[] header = new String[] { "Symbol", "Open", "High", "Low",
            "Bid Size", "Bid", "Ask", "Ask Size", "Last", "Last Size" };

    private Object[][] rowData;

    public MarketWindow(LiveEventEngine eventsEngine, String[] symbols) {
        this.eventsEngine = eventsEngine;

        this.symbols = symbols;
        
        rowData = new String[symbols.length][header.length];
        for (int i = 0; i < symbols.length; i++) {
            rowData[i][0] = symbols[i];
        }
        initUI();
        registerEvent();
    }

    private void initUI() {
        setLayout(new BorderLayout());

        tableModel = new DefaultTableModel();
        jTable = new JTable(tableModel);
        jTable = new JTable(tableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tableModel.setDataVector(rowData, header);
        
        jTable.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(jTable);
        add(scrollPane);
    }

    private void updateTable(TickEvent tickEvent) {
        for(int i = 0; i < symbols.length; i++) {
            if(symbols[i].equals(tickEvent.fullSymbol)) {
                if(tickEvent.price.floatValue() > 0) {
                    tableModel.setValueAt(UtilFunc.formatMoney(tickEvent.price), i, 8);   
                }
            }
        }
        tableModel.fireTableDataChanged();
    }

    private void registerEvent() {
        eventsEngine.registerHandler(EventType.TICK, this);
    }

    @Override
    public void handle(Event event) {
        if (event.getClass().isAssignableFrom(TickEvent.class)) {
            updateTable((TickEvent) event);
        }

    }

}
